package com.pricl.frame.core.mybatis;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class DynamicDataSource extends AbstractRoutingDataSource {

	// @Override
	// protected Object determineCurrentLookupKey() {
	// return DynamicDataSource.getDbType();
	// }
	public static boolean slaveFlag = false;

	private Object master;
	private List<Object> slaves;
	private int slaveSize = 0;

	private static final String KEY_MASTER = "master";
	private static final String KEY_SLAVE = "slave";

	@Override
	public void afterPropertiesSet() {
		Map<Object, Object> map = new HashMap<>();
		map.put(KEY_MASTER, master);
		setTargetDataSources(map);
		if (slaves != null && !slaves.isEmpty()) {
			slaveFlag = true;
			slaveSize = slaves.size();
			for (int i = 0; i < slaveSize; i++) {
				map.put(KEY_SLAVE + i, slaves.get(i));
			}
		}
		super.afterPropertiesSet();
	}

	@Override
	protected Object determineCurrentLookupKey() {
		// if(slaveFlag&&DataSourceSelectHolder.isSlave()){
		// //System.out.println("====slave");
		// }else{
		// //System.out.println("====master");
		// }
		if (slaveFlag && DataSourceSelectHolder.isSlave()) {
			return this.randomSlave();
		}
		return KEY_MASTER;
	}

	private Object randomSlave() {
		// return dataSources.get((int)(Math.random()*10)%dataSources.size());
		// incrementAndGet
		int index = (int) (Math.random() * 10) % slaveSize;
		// //System.out.print(index+"\n");
		// return slaves.get(index);
		return KEY_SLAVE + index;
		// return slaves.get((int)(Math.random()*10)%slaveSize);
	}

	public Object getMaster() {
		return master;
	}

	public void setMaster(Object master) {
		this.master = master;
	}

	public List<Object> getSlaves() {
		return slaves;
	}

	public void setSlaves(List<Object> slaves) {
		this.slaves = slaves;
	}

	public int getSlaveSize() {
		return slaveSize;
	}

	// private List<Object> dataSources;
	//
	// public void setDataSources(List<Object> dataSources) {
	// Map<Object, Object> map = new HashMap<>();
	// if (dataSources != null && !dataSources.isEmpty())
	// for (Object key : dataSources)
	// map.put(key, key);
	//
	// this.setTargetDataSources(map);
	// this.dataSources = dataSources;
	// }

}
